﻿#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QMessageBox>
#include <QFile>
#include <QDomDocument>
#include <QCoreApplication>
#include <QProcess>
#include "autoupdateplugin.h"

AutoUpdatePlugin::AutoUpdatePlugin(){
    m_manager = new QNetworkAccessManager();
    hasNewUpdateExe();
}

bool AutoUpdatePlugin::downNewListFile(){
    QString path = m_ip+":"+QString::number(m_port)+"/file/"+m_group+"/"+m_version_name;
    QEventLoop loop;
    QNetworkReply * reply = m_manager->get(QNetworkRequest(QUrl(path)));
    connect(reply,SIGNAL(finished()),&loop,SLOT(quit()));

    loop.exec();
    m_result = reply->readAll();
    QString list_file = "new_" + m_version_name;
    qDebug() << path << list_file << m_result;
    QFile file(list_file);
    if(m_result.isEmpty() || m_result.contains("404")){
        return false;
    }

    if(!file.open(QIODevice::WriteOnly)){
        return false;
    }else{
        file.write(m_result);
        file.close();
        return true;
    }
}

bool AutoUpdatePlugin::hasNewUpdateExe(){
    if(QFile::exists("new_tkgup.exe")){
        QFile::remove("tkgup.exe");
        QFile::rename("new_tkgup.exe","tkgup.exe" );
        return true;
    }
    return false;
}

bool AutoUpdatePlugin::checkoutVersion(){
    QFile file(m_version_name);
    if(!file.exists()){
        if(file.open(QIODevice::WriteOnly | QFile::Text)){
            file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?><update><version>0.0.0</version><filelist></filelist></update>");
            file.close();
        }else{
           QMessageBox::warning(0,"警告","无法创建version文件"+file.errorString(),QMessageBox::Ok);
        }

    }
    if(!file.open(QIODevice::ReadOnly | QFile::Text)){
        return false;
    }else{
        QByteArray content = file.readAll();
        file.close();
        QDomDocument doc;
        QDomDocument new_doc;
        if(doc.setContent(content) && new_doc.setContent(m_result)){
            QDomElement root = doc.documentElement();
            QDomElement new_root = new_doc.documentElement();
            if(root.tagName() == "update" && new_root.tagName() == "update"){
                QString version = root.elementsByTagName("version").at(0).toElement().text();
                m_version_num = new_root.elementsByTagName("version").at(0).toElement().text();
                if(!version.isEmpty() && !m_version_num.isEmpty()){
                    /*
                     * 思路：分成主版本和次版本解决并不更新主程序这一情况。因为是以版本号作为大小依据，而版本号又写在了主程序里面
                     * 这样当主程序的版本号和version.xml序号不一致，而且更新程序上显示也是不一致的
                     * 由于当前比较着急，这个暂时不实现。所以，就算更新辅程序，主程序也得更改版本号传上去
                     */
                    /*
                    QStringList myNumList = m_version_num.split(".");
                    if(myNumList.size() <= 3){
                        myNumList.append("000");
                    }else{
                        if(myNumList[3].length() == 1){
                        }
                    }
                    QStringList newNumList = version.split(".");
                    if(newNumList.size() == 3){
                        newNumList.append("000");
                    }else{
                    }*/
                    if(m_version_num > version){
                        qDebug() << "版本高，需要更新";
                        return true;
                    }else{
                        qDebug() << "版本低或相同，不需更新" << m_version_num << version;
                        return false;
                    }
                }else{
                    qDebug() << "版本为空！";
                    return false;
                }
            }
        }else{
            qDebug() << "设置xml文档错误";
            return false;
        }
    }

    return true;
}

bool AutoUpdatePlugin::execUpdateProc(){
    QStringList list;
    QString startExe = QCoreApplication::arguments()[0];
#ifdef Q_OS_WIN
    startExe = startExe.split("\\").last();
    qDebug() << "start " << startExe;//升级完成后，重启原程序
#else

#endif
    list << m_ip <<QString::number( m_port) << m_version_name << m_version_num << m_group << m_user << m_pass << startExe << m_update_window_name;
    qDebug() << m_update_exec_name << list;
    QProcess *exe = new QProcess(0);
    exe->start(m_update_exec_name,list);
//    exe->start("E:/CX/auto_update/update/build-update-Desktop_Qt_5_4_2_MinGW_32bit-Release/release"+m_update_exec_name,list);//测试用
    exe->waitForStarted();
    if(exe->state() == QProcess::Running){
        qDebug() << "启动完成";
        return true;
    }else{
        qDebug() << "启动失败";
        return false;
    }
}
void AutoUpdatePlugin::initUpdateExecName(const QString &name,const QString &window_name){
    m_update_exec_name = name;
    m_update_window_name = window_name;
}

void AutoUpdatePlugin::initRemoteConfig(const QString &ip, int port, const QString &list_file){
    m_ip =ip;
    m_port = port;
    m_version_name = list_file;
}

bool AutoUpdatePlugin::checkUpdate(const QString &group, const QString &user, const QString &pass){
    m_group = group;
    m_user = user;
    m_pass = pass;
    if( downNewListFile()){
        if(checkoutVersion()){
            if(QMessageBox::question(0,"更新确认",group + "有文件更新，是否现在更新？",QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes){
                return execUpdateProc();
            }
        }else{
            QFile::remove("new_"+m_version_name);
            return false;//无需更新
        }

    } else {
        QFile::remove("new_"+m_version_name);
        QMessageBox::information(0,"提醒","无法获取版本文件！");
        return false;
    }
    return false;
}
